import React, {useEffect, useState} from 'react'
import {Form, Button, Input, Modal, Row, Col, message, Upload, Select, DatePicker,InputNumber} from 'antd'
import {connect} from 'umi';
const FormItem = Form.Item;
const {Option} = Select;
const { TextArea } = Input;
import {getUploadUrl} from "@/utils/upload";
import moment from 'moment'
import {UploadOutlined} from '@ant-design/icons';
import {subsidyTypeList} from '@/utils/constant';

const formLayout = {
  labelCol: {span: 7},
};

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
};

let uploadedFiles = [];

const HousingAddForm = (props) => {
  const {onSubmit, onCancel, loading, visible, record,currentUser,type,applyMode} = props;
  const [form] = Form.useForm();
  const [fileName, setFileName] = useState(null);
  const [fileUploadUrls, setFileUploadUrls] = useState([]);
  const [title,setTitle] = useState(null);

  useEffect(() => {
    if (visible && currentUser) {
      setTitle(record ? '编辑' : '新建');
      form.setFieldsValue({...currentUser,unitname:currentUser.department,applyDate:moment()});
      if(record){
        form.setFieldsValue({...record,startDate:moment(record.startDate),endDate:moment(record.endDate),applyDate:moment(),sum:parseInt(record.monthlyAmount) * record.duration});
        let fileUrlList = record.fileUrl ? record.fileUrl.split(',') : [];
        setFileUploadUrls(fileUrlList);
        fileUrlList?.forEach((item,index) =>{
          uploadedFiles.push({
            uid: index,
            name: item.split('----')[1],
            status: 'done',
            url: item,
          })
        });
      }
    }
  }, [visible]);

  const fileList = {
    name: 'file',
    multiple: true,
    action: getUploadUrl(),
    data: {name: fileName},
    defaultFileList: uploadedFiles,
    beforeUpload(file) {
      setFileName(file.name)
    },
    onChange(res) {
      const {status} = res.file;
      if (status === 'done') {
        if (res.file.response.error) {
          message.success(`${res.file.response.error}`);
        } else {
          setFileUploadUrls([...fileUploadUrls,res.file.response ]);
          message.success(`${res.file.name} 文件上传成功`);
        }
      } else if (status === 'error') {
        message.error(`${res.file.name} 文件上传失败`);
      }
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.response);
      if (index > -1)
        urls.splice(index, 1);
      setFileUploadUrls(urls);
    }
  };

  const onFormCancel = () => {
    form.resetFields();
    uploadedFiles = [];
    setFileUploadUrls([]);
    onCancel();
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();
    onSubmit({
      ...fieldsValue, fileUrlList : fileUploadUrls,
      id:record && record.id,type:type,applyMode:applyMode
    });
    form.resetFields();
    uploadedFiles = [];
    setFileUploadUrls([]);
  };

  const computeTime = async () => {
    const fieldsValue = await form.getFieldsValue();
    form.setFieldsValue({endDate:moment(fieldsValue.startDate).add(fieldsValue.duration,'M')});
    if(typeof fieldsValue.duration === 'number' && typeof fieldsValue.monthlyAmount === 'string'){
      form.setFieldsValue({sum:parseInt(fieldsValue.monthlyAmount) * fieldsValue.duration});
    }
  };

  const  disabledDate = (current) => {
    return current && current < moment().endOf('month');
  };

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="name" label="申请姓名">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="orgname" label="所属公司">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="unitname" label="所属部门">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="jobname" label="现任岗位">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="applyDate" label="申请时间">
              <DatePicker disabled={true} className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="type" label="补贴类型" rules={[{required: true, message: '补贴类型不能为空'}]}>
              <Select disabled={true}>
                {subsidyTypeList?.map((item, index) => {
                  return (
                    <Option value={item.value} key={index}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="startDate" label="开始时间" rules={[{required: true, message: '开始时间不能为空'}]}>
              <DatePicker disabledDate={disabledDate} placeholder="请选择开始时间" picker="month" format="YYYY-MM" onChange={computeTime} className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="duration" label="时长" rules={[{required: true, message: '时长不能为空'}]}>
              <InputNumber style={{width: '100%'}} placeholder="请输入时长，单位（月）" max={36} min={0} onChange={computeTime}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="endDate" label="结束时间" rules={[{required: true, message: '结束时间不能为空'}]}>
              <DatePicker disabled={true} picker="month" format="YYYY-MM" className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="monthlyAmount" label="每月金额" rules={[{required: true, message: '每月金额不能为空'},({
              validator(rule,value) {
                let pattern = /(^[1-9]([0-9]*)$|^[0-9]$)/;
                if (pattern.test(value)) {
                  return Promise.resolve();
                }
                return Promise.reject('请输入数字类型的正确金额');
              },
            })]}>
              <Input suffix="元" onChange={computeTime}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="sum" label="补贴总金额">
            <Input disabled={true} suffix="元"/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name={type !== 4?'subsidyLocation':'subsidyReason'} label={type !== 4?'补贴地点':'补贴原因'} rules={[{required: true, message: type !== 4 ?'补贴地点不能为空':'补贴原因不能为空'}]}>
              <Input placeholder="请输入"/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="fileUrl" label="附件上传">
              <Upload {...fileList}>
                <Button>
                  <UploadOutlined/> 上传文件
                </Button>
              </Upload>
            </FormItem>
          </Col>
          <Col span={24}>
            <FormItem name="reason" labelCol={{span: 2}} label="申请说明">
              <TextArea rows={4} className='widthStyle'/>
            </FormItem>
          </Col>
        </Row>
      </>
    )
  };

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Button type="primary" onClick={() => handleSubmit()} loading={loading}>提交</Button>
      </>
    )
  };

  return (
    <Modal
      maskClosable={false}
      width='60%'
      destroyOnClose
      title={title + subsidyTypeList.find((item) => item.value === type).label + `申请`}
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      onClose={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        initialValues={{type:type}}
        form={form}
        style={{paddingTop: '24px'}}>
        {renderContent()}
      </Form>
    </Modal>
  )
};

export default connect(({user}) => ({
  currentUser: user.currentUser,
}))(HousingAddForm);
